from django import forms
from django.contrib.auth import authenticate

"""
A form to allow a user to log in.
""" 
class loginForm(forms.Form):
    username = forms.CharField(label=("Username"), max_length=30)
    password = forms.CharField(label=("Password"), widget=forms.PasswordInput)
    
    def authenticate(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username,
                                           password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'])
            elif not self.user_cache.is_active:
                raise forms.ValidationError(self.error_messages['inactive'])
        self.check_for_test_cookie()
        return self.user_cache

    def check_for_test_cookie(self):
        if self.request and not self.request.session.test_cookie_worked():
            raise forms.ValidationError(self.error_messages['no_cookies'])

    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        return self.user_cache

"""
A form to allow a user to register.
""" 
class RegistrationForm(forms.Form):
    username = forms.CharField(label=("Username"), max_length=30)
    email = forms.EmailField(label=("Email"), max_length=75)
    password = forms.CharField(label=("Password"), widget=forms.PasswordInput)
    password2 = forms.CharField(label=("Retype Password"), widget=forms.PasswordInput)
    